from datetime import datetime
from app import db
from sqlalchemy import Index
from app.utils.time_helper import safe_datetime_format

class Activity(db.Model):
    """活动模型"""
    __tablename__ = 'activities'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False, comment='活动标题')
    description = db.Column(db.Text, comment='活动描述')
    organizer_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='组织者ID')
    venue_id = db.Column(db.Integer, db.ForeignKey('venues.id'), comment='场馆ID')
    
    # 时间相关
    start_time = db.Column(db.DateTime, nullable=False, comment='开始时间')
    end_time = db.Column(db.DateTime, nullable=False, comment='结束时间')
    registration_deadline = db.Column(db.DateTime, comment='报名截止时间')
    
    # 场馆预订时间（如果与活动时间不同）
    venue_start_time = db.Column(db.DateTime, comment='场馆预订开始时间')
    venue_end_time = db.Column(db.DateTime, comment='场馆预订结束时间')
    
    # 参与者相关
    max_participants = db.Column(db.Integer, default=20, comment='最大参与人数')
    min_participants = db.Column(db.Integer, default=1, comment='最少参与人数')
    current_participants = db.Column(db.Integer, default=0, comment='当前参与人数')
    
    # 活动类型和标签
    activity_type = db.Column(db.String(50), comment='活动类型：sports=体育,social=社交,learning=学习,other=其他')
    tags = db.Column(db.Text, comment='活动标签，JSON格式存储')
    
    # 费用相关
    is_free = db.Column(db.Boolean, default=True, comment='是否免费')
    fee = db.Column(db.Numeric(10, 2), default=0, comment='活动费用')
    fee_description = db.Column(db.Text, comment='费用说明')
    
    # 状态和设置
    status = db.Column(db.String(20), default='open', comment='状态：open=开放,closed=关闭,cancelled=取消,finished=已结束')
    need_approval = db.Column(db.Boolean, default=False, comment='是否需要审核')
    allow_waitlist = db.Column(db.Boolean, default=True, comment='是否允许候补')
    
    # 联系方式
    contact_info = db.Column(db.Text, comment='联系方式说明')
    
    # 地址相关（如果不在场馆）
    location_name = db.Column(db.String(200), comment='活动地点名称')
    location_address = db.Column(db.Text, comment='活动地点地址')
    latitude = db.Column(db.Float, comment='纬度')
    longitude = db.Column(db.Float, comment='经度')
    
    # 额外信息
    requirements = db.Column(db.Text, comment='参与要求')
    notes = db.Column(db.Text, comment='备注信息')
    images = db.Column(db.Text, comment='活动图片，JSON格式存储')
    
    # 系统字段
    is_active = db.Column(db.Boolean, default=True, comment='是否活跃')
    view_count = db.Column(db.Integer, default=0, comment='浏览次数')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    organizer = db.relationship('User', foreign_keys=[organizer_id], backref='organized_activities')
    venue = db.relationship('Venue', backref='activities')
    participants = db.relationship('ActivityParticipant', backref='activity', lazy='dynamic')
    
    def __repr__(self):
        return f'<Activity {self.id}: {self.title}>'
    
    def to_dict(self, include_organizer=False, include_participants=False, include_venue=False):
        """转换为字典"""
        import json
        
        data = {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'organizer_id': self.organizer_id,
            'venue_id': self.venue_id,
            
            # 时间相关
            'start_time': safe_datetime_format(self.start_time),
            'end_time': safe_datetime_format(self.end_time),
            'registration_deadline': safe_datetime_format(self.registration_deadline),
            
            # 场馆预订时间（如果与活动时间不同）
            'venue_start_time': safe_datetime_format(self.venue_start_time),
            'venue_end_time': safe_datetime_format(self.venue_end_time),
            
            # 参与者相关
            'max_participants': self.max_participants,
            'min_participants': self.min_participants,
            'current_participants': self.current_participants,
            
            # 活动类型和标签
            'activity_type': self.activity_type,
            'tags': json.loads(self.tags) if self.tags else [],
            
            # 费用相关
            'is_free': self.is_free,
            'fee': float(self.fee) if self.fee else 0,
            'fee_description': self.fee_description,
            
            # 状态和设置
            'status': self.status,
            'need_approval': self.need_approval,
            'allow_waitlist': self.allow_waitlist,
            
            # 联系方式
            'contact_info': self.contact_info,
            
            # 地址相关
            'location_name': self.location_name,
            'location_address': self.location_address,
            'latitude': self.latitude,
            'longitude': self.longitude,
            
            # 额外信息
            'requirements': self.requirements,
            'notes': self.notes,
            'images': json.loads(self.images) if self.images else [],
            
            # 系统字段
            'is_active': self.is_active,
            'view_count': self.view_count,
            'created_at': safe_datetime_format(self.created_at),
            'updated_at': safe_datetime_format(self.updated_at)
        }
        
        # 包含组织者信息
        if include_organizer and self.organizer:
            data['organizer'] = self.organizer.to_dict()
        
        # 包含参与者信息
        if include_participants:
            # 获取状态为joined的参与者
            joined_participants = self.participants.filter_by(status='joined').all()
            data['participants'] = [p.to_dict(include_user=True) for p in joined_participants]
            # 同时更新当前参与人数以确保数据一致性
            data['current_participants'] = len(joined_participants)
            
            # 获取候补用户信息
            waitlist_participants = self.participants.filter_by(status='waitlist').order_by('created_at').all()
            data['waitlist_participants'] = []
            for idx, p in enumerate(waitlist_participants):
                waitlist_data = p.to_dict(include_user=True)
                waitlist_data['waitlist_position'] = idx + 1  # 候补排队位置
                data['waitlist_participants'].append(waitlist_data)
            
            # 候补总人数
            data['waitlist_count'] = len(waitlist_participants)
        
        # 包含场馆信息
        if include_venue and self.venue:
            data['venue'] = self.venue.to_dict()
            # 如果是场馆名称字段，也要包含进去
            data['venue_name'] = self.venue.name
        elif self.venue:
            # 至少包含场馆名称
            data['venue_name'] = self.venue.name
        else:
            data['venue_name'] = '未指定场馆'
        
        return data


class ActivityParticipant(db.Model):
    """活动参与者模型"""
    __tablename__ = 'activity_participants'
    
    id = db.Column(db.Integer, primary_key=True)
    activity_id = db.Column(db.Integer, db.ForeignKey('activities.id'), nullable=False, comment='活动ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    status = db.Column(db.String(20), default='joined', comment='状态：joined=已加入,left=已退出,pending=待审核,waitlist=候补')
    joined_at = db.Column(db.DateTime, default=datetime.now, comment='加入时间')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    user = db.relationship('User', backref='activity_participations')
    
    # 复合唯一索引
    __table_args__ = (
        Index('idx_activity_user', 'activity_id', 'user_id', unique=True),
    )
    
    def __repr__(self):
        return f'<ActivityParticipant activity_id={self.activity_id}, user_id={self.user_id}>'
    
    def to_dict(self, include_user=False):
        """转换为字典"""
        data = {
            'id': self.id,
            'activity_id': self.activity_id,
            'user_id': self.user_id,
            'status': self.status,
            'joined_at': safe_datetime_format(self.joined_at),
            'created_at': safe_datetime_format(self.created_at)
        }
        
        # 包含用户信息
        if include_user and self.user:
            user_data = {
                'id': self.user.id,
                'nickname': self.user.nickname,
                'avatar_url': self.user.avatar_url,
                'phone': self.user.phone if hasattr(self.user, 'phone') else None
            }
            data.update(user_data)
            # 添加别名字段以兼容前端
            data['participant_id'] = self.user.id
            data['participant_name'] = self.user.nickname
            data['participant_avatar'] = self.user.avatar_url
        
        return data 